package com.eqdd.yiqidian.ui.yiqichuang;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.internal.MDRootLayout;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.ListItem108Custom;
import com.eqdd.yiqidian.ListItem91Custom;
import com.eqdd.yiqidian.ListItem94Custom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ChuangwenCommonBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.box.ItemDecoration.DashDividerLineItemDecoration;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.box.span.NoLineClickSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.InputDialogActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ClickUtil;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.RefreshUtil;
import com.eqdd.yiqidian.utils.ScrollLoadMoreUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.header.MaterialHeader;
import com.xujiaji.happybubble.BubbleDialog;
import com.xujiaji.happybubble.BubbleLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 17-12-25  上午9:57.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class NewChuangCommentListActivity extends BaseActivity {

    private ListItem108Custom dataBinding;
    private boolean isMyComment;
    private int parentId;
    private String parentUserGuid;
    private int commentId;
    private String talkTo;
    private String talkContent;
    private int type;
    private MaterialDialog moreDialog;
    private int id;
    private int pageNum;
    private int firstCommentId;
    private SlimAdapterEx<ChuangwenCommonBean.SonCmetsBean> slimAdapterEx;
    private ChuangwenCommonBean yueCommentBean;
    private int dealPos;
    private boolean isCommentUp;
    private boolean isMore = false;
    private MaterialDialog reportDialog;
    private boolean isZan;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.list_item_108);
        initTopTitleBar(View.VISIBLE, "评论详情");
    }

    @Override
    public void initData() {
        yueCommentBean = (ChuangwenCommonBean) getIntent().getSerializableExtra(Config.BEAN);
        id = yueCommentBean.getId();
        firstCommentId = yueCommentBean.getId();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.addItemDecoration(new DashDividerLineItemDecoration(this).setDash(15));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_88, new SlimInjector<ChuangwenCommonBean.SonCmetsBean>() {
            @Override
            public void onInject(ChuangwenCommonBean.SonCmetsBean data, IViewInjector injector) {
                injector.with(R.id.tv_content, view -> {
                    TextView textView = (TextView) view;
                    SpannableString spStr = new SpannableString(data.getUserName() + ":" + " @" + data.getUpCmetUserName() + " " + data.getCommentContext());
                    NoLineClickSpan firstSpan = new NoLineClickSpan("#3423ff", v -> {

                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getUserGuid());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    NoLineClickSpan secondSpan = new NoLineClickSpan("#3423ff", v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(Config.GUID, data.getUpCmetUserGuid());
                        startActivity(UserCardActivity.class, bundle);
                    });
                    spStr.setSpan(firstSpan, 0, data.getUserName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), spStr.toString().indexOf("@") + 1 + data.getUpCmetUserName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    textView.setMovementMethod(LinkMovementMethod.getInstance());
                    textView.setText(spStr);
                });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    ChuangwenCommonBean.SonCmetsBean dataItem = slimAdapterEx.getDataItem(position);
                    isMyComment = dataItem.getUserGuid().equals(AppConstent.user.getGuid());
                    parentId = dataItem.getId();
                    parentUserGuid = dataItem.getUserGuid();
                    commentId = dataItem.getId();
                    talkTo = dataItem.getUserName();
                    talkContent = dataItem.getCommentContext();
                    type = 2;
                    isZan = dataItem.isPraised();
                    isCommentUp = false;
                    dealPos = position;
                    showMoreDialog();
                })
                .setOnItemLongClickListener((recyclerView1, position, v) -> {
                    ChuangwenCommonBean.SonCmetsBean dataItem = slimAdapterEx.getDataItem(position);
                    showReplyContent(v, dataItem.getUpCmetContext());
                    return true;
                });
        initView();
    }

    private void initView() {
        ImageUtil.setCircleImage(yueCommentBean.getIphoto(), dataBinding.ivHead);
        dataBinding.tvName.setText(yueCommentBean.getUserName());
        dataBinding.tvTime.setText(yueCommentBean.getCreateTime());
        dataBinding.stvComment.setText(yueCommentBean.getLowerCount() + "");
        dataBinding.stvZan.setText(yueCommentBean.getPraiseCount() + "");
        if (yueCommentBean.isIsZan()) {
            dataBinding.stvZan.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
        } else {
            dataBinding.stvZan.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_hint));
        }
        ClickUtil.click(dataBinding.stvZan, () -> HttpUtil.zanChuangComment(yueCommentBean.getId(), false, !yueCommentBean.isIsZan(), () -> {
            updateZan(!yueCommentBean.isIsZan());

        }));
        dataBinding.stvComment.setDrawable(getResources().getDrawable(R.mipmap.ic_comment_hint));
        dataBinding.tvContent.setText(yueCommentBean.getCommentContext());
        ClickUtil.click(dataBinding.stvComment, () -> {
            parentId = yueCommentBean.getId();
            talkTo = yueCommentBean.getUserName();
            parentUserGuid = yueCommentBean.getUserGuid();
            firstCommentId = yueCommentBean.getId();
            isCommentUp = true;
            talkTo();
        });
        ClickUtil.click(dataBinding.tvContent, () -> {
            isMyComment = yueCommentBean.getUserGuid().equals(AppConstent.user.getGuid());
            parentId = yueCommentBean.getId();
            parentUserGuid = yueCommentBean.getUserGuid();
            firstCommentId = yueCommentBean.getId();
            commentId = yueCommentBean.getId();
            talkTo = yueCommentBean.getUserName();
            talkContent = yueCommentBean.getCommentContext();
            isZan = yueCommentBean.isIsZan();
            type = 1;
            isCommentUp = true;
            showMoreDialog();
        });

    }

    private void updateZan(boolean isZan) {
        yueCommentBean.setIsZan(isZan);
        dataBinding.stvZan.setDrawable(getResources().getDrawable(yueCommentBean.isIsZan() ? R.mipmap.ic_heart_red : R.mipmap.ic_heart_hint));
        yueCommentBean.setPraiseCount(yueCommentBean.getPraiseCount()+(yueCommentBean.isIsZan() ? 1 : -1));
        dataBinding.stvZan.setText( yueCommentBean.getPraiseCount()+ "");
    }

    @Override
    public void setView() {
        dataBinding.coolRefreshView.setPullHeader(new MaterialHeader(this), true);
        RefreshUtil.openRefresh(dataBinding.coolRefreshView, coolRefreshView -> refresh(true));
        ScrollLoadMoreUtil.loadMore(dataBinding.nestedScrollView, () -> {
            if (isMore) {
                refresh(false);
            }
        });
        dataBinding.coolRefreshView.setRefreshing(true);
    }

    private void refresh(boolean isRefresh) {
        pageNum = isRefresh ? 0 : pageNum;
        OkGo.<ZhangPageResultBean<List<ChuangwenCommonBean.SonCmetsBean>>>post(HttpConfig.BASE_URL + HttpConfig.CHUANG_COMMENT_CHILDREN_LIST)
                .params("page", pageNum)
                .params("userGuid", AppConstent.user.getGuid())
                .params("commentId", id)
                .converter(new JsonConverter<ZhangPageResultBean<List<ChuangwenCommonBean.SonCmetsBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                }).adapt(new FlowableBody<>())
                .map(listZhangPageResultBean -> {
                    if (listZhangPageResultBean.getItems() == null || listZhangPageResultBean.getItems().size() < 10) {
                        isMore = false;
                    } else {
                        isMore = true;
                    }
                    pageNum = listZhangPageResultBean.getNextpage();
                    return listZhangPageResultBean.getItems();
                })
                .filter(sonCmetsBeans -> sonCmetsBeans != null)
                .subscribe(sonCmetsBeans -> {
                            if (isRefresh) {
                                slimAdapterEx.updateData(sonCmetsBeans);
                            } else {
                                int size = slimAdapterEx.getData().size();
                                slimAdapterEx.getData().addAll(sonCmetsBeans);
                                slimAdapterEx.notifyItemRangeInserted(size, sonCmetsBeans.size());
                            }
                        },
                        e -> {
                            System.out.println(e);
                            if (isRefresh) {
                                ToastUtil.showShort(Config.SERVER_ERROR);
                                dataBinding.coolRefreshView.setRefreshing(false);
                            }
                        },
                        () -> {
                            if (isRefresh) {
                                dataBinding.coolRefreshView.setRefreshing(false);
                            }
                        });
    }

    private void showMoreDialog() {
        if (moreDialog == null) {
            SlimAdapterEx<ChuangwenCommonBean.SonCmetsBean> slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                @Override
                public void onInject(Object data, IViewInjector injector) {

                    injector.text(R.id.tv_content, (String) data);
                }
            }).updateData(new ArrayList());
            moreDialog = new MaterialDialog.Builder(this)
                    .adapter(slimAdapterEx, new LinearLayoutManager(this))
                    .build();
            moreDialog.getRecyclerView().addItemDecoration(new SectionDividerItemDecoration(this)
                    .setHeadHeight(0)
                    .setRightPadding(DensityUtil.percentW(40))
                    .setLeftPadding(DensityUtil.percentW(40))
                    .setLastBootomHeght(0));
            ItemClickSupport.addTo(moreDialog.getRecyclerView())
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        switch (position) {
                            case 0:
                                talkTo();
                                break;
                            case 1:
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 将文本内容放到系统剪贴板里。
                                if (cm != null) {
                                    cm.setPrimaryClip(ClipData.newPlainText("Lable", talkContent));
                                }
                                ToastUtil.showShort("已复制");
                                break;
                            case 2:
                                HttpUtil.zanChuangComment(commentId, false, !isZan, () -> {
                                    if (isCommentUp) {
                                        updateZan(!isZan);
                                    } else {
                                        this.slimAdapterEx.getDataItem(dealPos).setPraised(!isZan);
                                    }
                                });
                                break;
                            case 3:
                                if (isMyComment) {
                                    HttpUtil.deleteChuangComment(NewChuangCommentListActivity.this, commentId, () -> {
                                        if (isCommentUp) {
                                            finish();
                                        } else {
                                            this.slimAdapterEx.getData().remove(dealPos);
                                            this.slimAdapterEx.notifyItemRemoved(dealPos);
                                        }
                                    });
                                } else {
                                    if (reportDialog == null) {
                                        reportDialog = new MaterialDialog.Builder(this)
                                                .items("广告或垃圾信息", "其它")
                                                .itemsCallbackSingleChoice(0, (dialog, view, which, text) -> {
                                                    HttpUtil.reportChuangArticle(commentId, text.toString(), 2, ((TextView) reportDialog.getView().findViewById(R.id.et_content)).getText().toString().trim(), () -> {

                                                    });
                                                    return true;
                                                })
                                                .content("请选择举报类型")
                                                .positiveText("确定")
                                                .negativeText("取消")
                                                .build();
                                        if (reportDialog.getView() instanceof MDRootLayout) {
                                            EditText editView = (EditText) DataBindingUtil.inflate(getLayoutInflater(), R.layout.list_item_90, null, false).getRoot();
                                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(800, 130);
                                            layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                                            editView.setLayoutParams(layoutParams);
                                            editView.setMaxHeight(300);
                                            ((LinearLayout) ((ViewGroup) reportDialog.getView()).getChildAt(1)).addView(editView);
                                        }
                                    }
                                    reportDialog.show();
                                    break;
                                }
                                break;
                        }
                        moreDialog.dismiss();
                    });
        }
        SlimAdapterEx slimAdapterExMore = (SlimAdapterEx) moreDialog.getRecyclerView().getAdapter();
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("回复");
        objects.add("复制");
        objects.add(isZan ? "取消赞" : "赞");
        objects.add(isMyComment ? "删除" : "举报");
        slimAdapterExMore.updateData(objects);
        moreDialog.show();

    }

    private void talkTo() {
        Bundle bundle = new Bundle();
        bundle.putString(Config.TALK_TO, talkTo);
        startActivityForResult(InputDialogActivity.class, bundle, Config.INPUT);
    }

    private void showReplyContent(View view, String content) {
        ListItem91Custom inflate = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.list_item_91, null, false);
        inflate.tvContent.setText(content);
        BubbleLayout bl = new BubbleLayout(this);
        bl.setBubbleColor(Color.parseColor("#744e37"));
        bl.setShadowColor(Color.RED);
        bl.setLookLength(DensityUtil.percentW(15));
        bl.setLookWidth(DensityUtil.percentW(20));
        Rect viewRect = new Rect();
        view.getGlobalVisibleRect(viewRect);
        new BubbleDialog(this)
                .setClickedView(view)
                .addContentView(inflate.getRoot())
                .setPosition(viewRect.centerY() > (WindowUtil.csh >> 1) ? BubbleDialog.Position.TOP : BubbleDialog.Position.BOTTOM)
                .calBar(true)
                .setOffsetY(DensityUtil.percentW(viewRect.centerY() > (WindowUtil.csh >> 1) ? 15 : -15))
                .setBubbleLayout(bl)
                .setTransParentBackground()
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.INPUT && resultCode == Config.SUCCESS) {
            String content = data.getStringExtra(Config.CONTENT);
            HttpUtil.commentChuangArticle(NewChuangCommentListActivity.this, id, parentId, content, parentUserGuid, firstCommentId, (commentBean) -> {
                if (isCommentUp) {
                    slimAdapterEx.getData().add(0, (ChuangwenCommonBean.SonCmetsBean) commentBean);
                    slimAdapterEx.notifyItemInserted(0);
                } else {
                    slimAdapterEx.getData().add((ChuangwenCommonBean.SonCmetsBean) commentBean);
                    slimAdapterEx.notifyItemInserted(slimAdapterEx.getData().size() - 1);
                }
            });
        }
    }
}
